﻿namespace Grep.SharePoint.SmartDocuments
{
    using System;
    using System.Web.UI.WebControls;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.ApplicationPages;

    public class TemplateLibraryConnectorConfig : ListPageBase
    {
        protected RadioButton RadEnableTLCNo;
        protected RadioButton RadEnableTLCYes;
        protected Label TestLabel;
        protected TextBox TextError;
        protected TextBox TextSourceDescField;
        protected TreeView TreeSourceDocLib;

        protected void BtnSave_Click(object sender, EventArgs e)
        {
            bool enabled = RadEnableTLCYes.Checked;
            string webId = "";
            string listId = "";
            string descriptionFieldName = TextSourceDescField.Text;

            string[] idCombo = TreeSourceDocLib.SelectedValue.Split('|');
            if (idCombo.Length == 2)
            {
                webId = idCombo[0];
                listId = idCombo[1];
            }
            else if (enabled)
            {
                // Idstring is corrupt, so show an error and bail
                ShowError("Please select a valid Document Library in the tree view.");
                return;
            }

            // Establish a setting bag and save it to the list
            var settings = new TemplateLibraryConnectorSettings
                               {
                                   WebId = webId,
                                   TemplateListId = listId,
                                   DescriptionFieldName = descriptionFieldName,
                                   Enabled = enabled
                               };
            TemplateLibraryConnectorSettings.SaveToList(List, settings);

            HideError();
        }

        /// <summary>
        /// Will move up the tree, looking for the highest possible web hit user can
        /// access.
        /// </summary>
        private static SPWeb FindHighestWebForCurrentUser(SPWeb web)
        {
            while (!web.IsRootWeb &&
                   web.ParentWeb != null &&
                   web.ParentWeb.DoesUserHavePermissions(SPBasePermissions.ViewPages))
            {
                web = web.ParentWeb;
            }
            return web;
        }

        private void HideError()
        {
            TextError.Visible = false;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (!Page.IsPostBack)
            {
                HideError();

                TemplateLibraryConnectorSettings settings;
                try
                {
                    settings = TemplateLibraryConnectorSettings.LoadFromList(List) ??
                               TemplateLibraryConnectorSettings.Default;
                }
                catch (Exception ex)
                {
                    // Suppress settings: Load from defaults
                    settings = TemplateLibraryConnectorSettings.Default;
                    ShowError("Error loading list settings - Loaded default values instead.<br/><br/>Details: {0}",
                              ex.Message);
                }

                // Load enabled state
                RadEnableTLCYes.Checked = settings.Enabled;
                RadEnableTLCNo.Checked = !RadEnableTLCYes.Checked;

                // Populate the List tree, and select the saved value
                SPWeb rootWeb = FindHighestWebForCurrentUser(SPContext.Current.Web);
                var rootNode = new TreeNode("Site Content", "")
                                   {Expanded = true, SelectAction = TreeNodeSelectAction.None};
                TreeSourceDocLib.Nodes.Add(rootNode);
                PopulateTree(rootNode, rootWeb, settings.TemplateListId);

                // Load the description field
                TextSourceDescField.Text = settings.DescriptionFieldName;
            }
        }

        private static void PopulateTree(TreeNode node, SPWeb web, string selectedListId)
        {
            var webNode = new TreeNode(web.Title,
                                       "",
                                       "/_layouts/images/folder.gif")
                              {Expanded = true, SelectAction = TreeNodeSelectAction.None};
            node.ChildNodes.Add(webNode);

            // Dive into child webs
            foreach (SPWeb childWeb in web.Webs)
            {
                try
                {
                    if (childWeb.DoesUserHavePermissions(SPBasePermissions.ViewPages))
                    {
                        PopulateTree(webNode, childWeb, selectedListId);
                    }
                }
                finally
                {
                    childWeb.Dispose();
                }
            }

            // Filter document libraries
            foreach (SPList list in web.Lists)
            {
                if (list is SPDocumentLibrary &&
                    !list.Hidden)
                {
                    var listNode = new TreeNode(list.Title,
                                                string.Format("{0}|{1}", web.ID, list.ID),
                                                "/_layouts/images/list.gif")
                                       {SelectAction = TreeNodeSelectAction.Select};
                    if (list.ID.ToString().Equals(selectedListId))
                    {
                        listNode.Selected = true;
                    }
                    webNode.ChildNodes.Add(listNode);
                }
            }
        }

        private void ShowError(string format, params string[] args)
        {
            TextError.Text = string.Format(format, args);
            TextError.Visible = true;
        }
    }
}